<template>
  <div class="updateExceptionWrap h100" style="height: calc(100% - 60px);padding-right:10px;">
    <a-form layout="vertical">
      <a-row :gutter="[16, 0]">
        <a-col :span="6">
          <a-form-model-item label="VIN码">
            <a-input size="small" v-model="queryParams.vin" :allow-clear="true" @keyup.enter="searchData" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="ECUID">
            <a-input
              :placeholder="$t('pleaseInput') + 'ECU ID'"
              size="small"
              v-model="queryParams.ecuId"
              :allow-clear="true"
            />
          </a-form-model-item>
        </a-col>
        <!-- ECU名称 -->
        <a-col :span="6">
          <a-form-model-item label="ECU名称">
            <a-input
              :placeholder="$t('pleaseInput') + 'ECU名称'"
              size="small"
              v-model="queryParams.ecuName"
              :allow-clear="true"
            />
          </a-form-model-item>
        </a-col>
        <!-- 任务名称 -->
        <a-col :span="6">
          <a-form-model-item :label="$t('campaignName')">
            <a-input
              :placeholder="$t('pleaseInput') + '任务名称'"
              size="small"
              v-model="queryParams.taskName"
              :allow-clear="true"
            />
          </a-form-model-item>
        </a-col>

        <!-- 升级结果下拉框 -->
        <a-col :span="6">
          <a-form-model-item label="ECU升级结果">
            <a-select
              :showSearch="true"
              mode="multiple"
              :maxTagCount="1"
              :placeholder="'ECU升级结果'"
              :allow-clear="true"
              v-model="queryParams.ecuUpgradeResult"
              style="width: 100%"
              @change="searchData"
            >
              <a-select-option value="正在升级"> 正在升级 </a-select-option>
              <a-select-option value="未完成"> 未完成 </a-select-option>
              <a-select-option value="安装成功"> 安装成功 </a-select-option>
              <a-select-option value="安装失败"> 安装失败 </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <!-- 升级流水号 -->
        <a-col :span="6">
          <a-form-model-item :label="$t('升级流水号')">
            <a-input
              :placeholder="$t('pleaseInput') + '升级流水号'"
              size="small"
              v-model="queryParams.processId"
              :allow-clear="true"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item :label="$t('ECU状态码')">
            <a-input :placeholder="$t('pleaseInput') + 'ECU状态码'" size="small" v-model="queryParams.ecuStatus" :maxLength="4"
            :allow-clear="true"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="6" style="margin-top:22px;">
          <div class="searchBtns">
            <a-button-group>
              <auth-button type="primary" :auth="statisticsPerms.monitor.detail" @click="searchData">
                <i class="iconfont icon-chazhao" />{{ $t('inquiry') }}
              </auth-button>
              <a-button @click="clearCondition"> <i class="iconfont icon-qingkong" />{{ $t('clear') }} </a-button>
            </a-button-group>
            <!-- 导出 -->
            <auth-button
              type="primary"
              :loading="exportingDetail"
              :auth="statisticsPerms.monitor.detailExport"
              @click="exportDetail"
            >
              <i class="iconfont icon-xiazai" />导出
            </auth-button>
            <question-mark-tip
              tip-title="仅支持导出1w条数据"
              :popupContainer="$commonFun.getPopupContainer"
            ></question-mark-tip>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <div class="updateExceptionList commonTableSty">
      <s-table
        class="h100"
        ref="table"
        size="default"
        rowKey="id"
        :columns="istableCol?isColumns:columns"
        :data="loadData"
        :customRow="customRow"
        :rowClassName="rowClassName"
      >
        <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
          <table-ellipsis :text="text || '-'" :key="column.key"></table-ellipsis>
        </template>
        <template slot="ecuSoftCode" slot-scope="text, record">
          <span v-if="text != record.cloudEcuSoftCode" style="color: red">
            <b>{{ record.ecuSoftCode }}</b></span>
          <span v-else>{{ record.ecuSoftCode }}</span>
        </template>
        <template #displayDetail="text">
          <table-ellipsis :text="text ? '是' : '否'"></table-ellipsis>
        </template>
        <template #isDeleteDiagnosticTroubleCode="text">
          <table-ellipsis :text="text ? '是' : '否'"></table-ellipsis>
        </template>
        <template #isConfigFile="text">
          <table-ellipsis :text="text ? '是' : '否'"></table-ellipsis>
        </template>
        <template #reportingTime="text">
          <table-ellipsis :text="$commonFun.getDateMinuteStr(text)"></table-ellipsis>
        </template>

        <template slot="operation" slot-scope="text, record">
          <auth-button
            v-if="text.displayDetail"
            @click="ecuListDetail(record)"
            :auth="statisticsPerms.monitor.monitorEcuDetail"
            type="primary"
            :ghost="true"
            size="small"
          >
            <i class="iconfont icon-yanjing" />查看</auth-button
          >
        </template>
      </s-table>
    </div>
  </div>
</template>
<script>
import { fotaMonitorColumns } from '@/views/statistics/monitorDetail/config/list'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { STable } from '@/components'
import logApi from '@/api/modules/log'
import statisticsApi from '@/api/modules/statistics'
import fileApi from '@/api/modules/system/fileUpload'
import { downloadBlobFile } from '@/utils/functions'
import AuthButton from '@/components/AuthButton'
import AuthText from '@/components/AuthText'
import { statisticsPerms } from '@/config/permission/index'
import moment from 'moment'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'

const initQueryParams = {
  taskName: '',
  // 车型
  modelIds: [],
  upgradeResult: undefined,
  createTimeLte: '',
  createTimeGte: '',
  ecuUpgradeResult: undefined,
  // 升级流水号
  processId: '',
  ecuStatus: undefined
}
export default {
  components: {
    STable,
    TableEllipsis,
    AuthButton,
    AuthText,
    QuestionMarkTip
  },
  props: {
    EcuUpgradeDetailListParameters: {
      type: Object,
      default () {
        return {}
      }
    },
    istableCol: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const quchuczCol = [...fotaMonitorColumns]
    quchuczCol.splice(19, 1)
    return {
      moment,
      statisticsPerms,
      exporting: false,
      columns: fotaMonitorColumns,
      isColumns: quchuczCol,
      queryParams: {
        ...initQueryParams,
        vin: '',
        batchId: '',
        checkSeqNo: '',
        ecuId: undefined,
        ecuName: undefined,
        vehicleId: undefined,
        taskId: undefined,
        taskName: undefined,
        processId: undefined
      },
      // 升级异常车型分布数据
      modelStatisticsData: [],
      loadingModelStatisticsData: true,
      pageInfo: {
        pageSize: 14,
        pageNo: 1
      },
      totalCount: 0,
      exportingDetail: false,
      exportingDistribute: false,
      carUpgradeInfo: {},
      tableCurrRowId: '',
      tableData: []
    }
  },
  computed: {
    commonColumns () {
      return this.columns.filter((item) => !item.special)
    }
  },
  created () {
    this.queryParams.vin = this.$route.query.vin
    this.queryParams.batchId = this.$route.query.batchId
    this.queryParams.checkSeqNo = this.$route.query.checkSeqNo
    this.queryParams.taskId = this.$route.query.taskId
    this.queryParams.vehicleId = this.$route.query.vehicleId
    this.queryParams.ecuId = this.$route.query.ecuId
    this.queryParams.processId = this.$route.query.processId
    this.queryParams.taskName = this.$route.query.taskName
    // this.$route.meta.title = "升级监控 / " + this.queryParams.vin
    if (Object.keys(this.EcuUpgradeDetailListParameters).length !== 0) {
      this.queryParams.vin = this.EcuUpgradeDetailListParameters.vin
      this.queryParams.batchId = this.EcuUpgradeDetailListParameters.batchId
      this.queryParams.checkSeqNo = this.EcuUpgradeDetailListParameters.checkSeqNo
      this.queryParams.taskId = this.EcuUpgradeDetailListParameters.taskId
      this.queryParams.processId = this.EcuUpgradeDetailListParameters.processId
      this.queryParams.taskName = this.EcuUpgradeDetailListParameters.taskName
    }
  },
  watch: {
    'queryParams.taskName'(val, old) {
      if (val === '') {
        // this.queryParams.processId = ''
        this.queryParams.taskId = ''
        this.queryParams.taskName = ''
        this.queryParams.batchId = ''
      }
    },
    'tableData.length' (val, old) {
      if (val > 0) {
        this.carUpgradeInfo = {
          taskId: this.tableData[0].taskId,
          vehicleId: this.tableData[0].vehicleId,
          vin: this.queryParams.vin,
          ecuModuleId: this.tableData[0].ecuId,
          checkSeqNo: this.queryParams.checkSeqNo,
          ecuName: this.tableData[0].ecuName,
          processId: this.tableData[0].processId
        }
        this.tableCurrRowId = this.tableData[0].id
        if (this.istableCol) {
          this.$emit('carUpgradeInfoChange', this.carUpgradeInfo)
        }
      }
    }
  },
  methods: {
    resize () {
      this.$refs.table.getDomHeight();
    },
    // 点击行
    customRow (record, index) {
      return {
        on: {
          click: () => {
            this.carUpgradeInfo = {
              taskId: record.taskId,
              vehicleId: record.vehicleId,
              vin: this.queryParams.vin,
              ecuModuleId: record.ecuId,
              checkSeqNo: this.queryParams.checkSeqNo,
              ecuName: record.ecuName,
              processId: record.processId
            }
            this.tableCurrRowId = record.id
            if (this.istableCol) {
              this.$emit('carUpgradeInfoChange', this.carUpgradeInfo)
            }
          }
        }
      }
    },
    // 行高亮
    rowClassName (record, index) {
      if (this.istableCol) {
        return (record.id === this.tableCurrRowId) ? 'blue' : 'white'
      }
      return record.displayDetail ? 'white' : 'gray'
    },
    searchData () {
      this.refreshData()
    },
    clearCondition () {
      console.log('执行了')
      this.queryParams = { ...initQueryParams }
      // this.queryParams.vin = this.$route.query.vin
      this.queryParams.batchId = this.$route.query.batchId
      this.queryParams.checkSeqNo = this.$route.query.checkSeqNo
      this.queryParams.taskId = this.$route.query.taskId
      this.queryParams.processId = this.$route.query.processId
      //this.queryParams.ecuId = this.$route.query.ecuId
      this.$set(this.queryParams, 'vin', this.$route.query.vin)
      this.$set(this.queryParams, 'taskName', this.$route.query.taskName)
      if (Object.keys(this.EcuUpgradeDetailListParameters).length !== 0) {
        this.queryParams.vin = this.EcuUpgradeDetailListParameters.vin
        this.queryParams.batchId = this.EcuUpgradeDetailListParameters.batchId
        this.queryParams.checkSeqNo = this.EcuUpgradeDetailListParameters.checkSeqNo
        this.queryParams.taskId = this.EcuUpgradeDetailListParameters.taskId
        this.queryParams.processId = this.EcuUpgradeDetailListParameters.processId
        this.queryParams.taskName = this.EcuUpgradeDetailListParameters.taskName
      }
      this.searchData()
    },
    selectCarModel (val) {
      this.queryParams.modelIds = val
    },
    // 导出明细
    exportDetail () {
      this.exportingDetail = true
      statisticsApi
        .exportFOTAUpgradeList(this.queryParams)
        .then((res) => {
          downloadBlobFile(
            res,
            '升级列表-' +
              this.queryParams.vin +
              '-' +
              this.queryParams.batchId +
              '-' +
              moment().format('YYYYMMDD-HHmmss') +
              '.xlsx'
          )
        })
        .finally(() => {
          this.exportingDetail = false
        })
    },
    // 导出分布
    exportDistribute () {
      this.exportingDistribute = true
      logApi
        .exportClientLogModelStatistics(this.queryParams)
        .then((res) => {
          downloadBlobFile(res, this.$t('updateExceptionModelDistribute') + '.xlsx')
        })
        .finally(() => {
          this.exportingDistribute = false
        })
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParams))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      this.tableData = []
      const apiPromise = statisticsApi.getOtaUpdateHisDetailList({ ...parameter, ...JnqueryParam })
      return new Promise((resolve, reject) => {
        return apiPromise.then(res => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    refreshData (isToFirstPage = true) {
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.table.loadData(obj)
    },
    changePageSize (page) {
      this.pageInfo.pageNo = page
      this.loadData()
    },
    // 下载日志
    downloadFile (file) {
      fileApi.downloadFileToLocal({ id: file.id }).then((res) => {
        downloadBlobFile(res, file.name)
      })
    },
    ecuListDetail (record) { 
      console.log(record)
      this.$router.push({
        path: '/statistics/monitorList/detail/ecu',
        query: {
          taskId: record.taskId,
          vehicleId: record.vehicleId,
          vin: this.queryParams.vin,
          ecuModuleId: record.ecuId,
          checkSeqNo: this.queryParams.checkSeqNo,
          ecuName: record.ecuName,
          processId: record.processId
        }
      })
      return
    },
    selectDateRange (date, dateString) {
      this.queryParams.createTimeLte = dateString[0]
      this.queryParams.createTimeGte = dateString[1]
    }
  }
}
</script>
<style lang="less" scoped>
.updateExceptionWrap {
  display: flex;
  flex-direction: column;
  .updateExceptionList {
    flex: 1 0 0;
    // overflow: auto;
  }
}
::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
 /deep/.ant-table-tbody .white{
    background-color: white !important;
  }
  /deep/.ant-table-tbody .blue{
    background-color: #d8e4e6 !important;
  }
/deep/.ant-table-tbody .gray{
  background-color: #ccc !important;
}
</style>
